<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="Add">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" prop="page" width="120" />
              <el-table-column label="角色名称" prop="name" width="240" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edmFn(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination layout="total, sizes,prev,pager,next,jumper" :page-size="pageParams.pagesize" :page-sizes="[2, 4, 6, 8]" :total="total" :current-page.sync="curpage" @current-change="hCurrentChange" @size-change="handleSizeChange" />
            </el-row>
            <!-- 简单弹窗不用封装 -->
            <el-dialog :title="edit?'编辑角色':'新增角色'" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialog" @close="hClose">
              <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="roleForm.name" />
                </el-form-item>
                <el-form-item label="角色描述">
                  <el-input v-model="roleForm.description" />
                </el-form-item>
              </el-form>
              <!-- 底部 -->
              <el-row slot="footer" type="flex" justify="center">
                <el-col :span="6">
                  <el-button size="small" @click="showDialog=false">取消</el-button>
                  <el-button size="small" type="primary" @click="submit">确定</el-button>
                </el-col>
              </el-row>
            </el-dialog>
            <!-- 简单弹窗不用封装 -->
            <el-dialog title="分配权限" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialogAssign">
              <!-- 子组件 -->
              <assignPermission :id="id" ref="assignPermission" @hclose="hcloseit" />
              <!-- 底部 -->
              <el-row slot="footer" type="flex" justify="center">
                <el-col :span="6">
                  <el-button size="small" @click="hcloseit">取消</el-button>
                  <el-button size="small" type="primary" @click="hSave">确定</el-button>
                </el-col>
              </el-row>
            </el-dialog>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script>
import assignPermission from './assignPermission.vue'
import { getRoles, deleteRole, addRole, updateRole } from '@/api/setting.js/'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      id: '',
      activeName: 'first',
      roles: [],
      edit: false,
      curpage: 1,
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 2 // 每页两条  --- 要与pagination中page-size一致
      },
      total: 0, // 总的数据条数
      page: 0,
      showDialog: false,
      showDialogAssign: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 表格中最大的页码
    maxNum() {
      return Math.ceil(this.total / this.pageParams.pagesize)
    }
    // 最后一页是不是满的
    // isLastPageFulled: function () {
    //   return this.total % this.pageParams.pagesize === 0
    // }
  },
  created() {
    this.getRolesFn()
  },

  methods: {
    hAssign(id) {
      this.showDialogAssign = true
      this.id = id
      this.$nextTick(() => {
        // 弹窗弹出时调用获取树状数据方法，避免了在created里的一次调用
        this.$refs.assignPermission.loadPermissionById()
      })
    },
    async getRolesFn() {
      const res = await getRoles(this.pageParams)
      console.log(res)
      this.roles = res.data.rows
      this.total = res.data.total
      this.curpage = this.pageParams.page
      this.pageFn()
    },
    hCurrentChange(curPage) {
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.getRolesFn()
    },
    handleSizeChange(pagesize) {
      // 1. 更新条数这个pagesize是分页组件页面条数更新时触发的方法自动获取到更改后的条数
      // 传递到这里给 this.pageParams.pagesize 赋值，再在分页组件中被page-size监听到，从而显示更改后的条数
      // 用getRolesFn重新发送请求更新页面
      this.pageParams.pagesize = pagesize
      // 2. 重发请求
      this.getRolesFn()
    },
    // 序号按顺序排，先找出每页第一个序号是几，然后再依次加index下标值这样就实现了按需排号
    pageFn() {
      const pageNumber = this.pageParams.page * this.pageParams.pagesize - this.pageParams.pagesize + 1
      this.page = pageNumber
      this.roles.forEach((item, index) => {
        return index === 0 ? (item.page = this.page) : (item.page = this.page + index)
      })
      console.log('roles', this.roles)
    },
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        // 1. 提示
        this.$message.success('删除成功')
        // 2. 重新请求
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page === 0) {
            this.pageParams.page = 1
          }
        }
        this.getRolesFn()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log('编辑功能', res)
        this.getRolesFn()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    // 用户点击了删除
    hDel(id, e) {
      e.path.find(item => item.tagName === 'BUTTON').blur()
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(err => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 添加角色
    Add() {
      this.showDialog = true
      this.edit = false
    },
    async AddFn() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)
        if (this.total % this.pageParams.pagesize === 0) {
          this.pageParams.page = this.maxNum + 1
        } else {
          // 想查看最新添加的数据，要跳到最大页码
          this.pageParams.page = this.maxNum
        }
        this.getRolesFn()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('添加失败')
        console.log(err)
      }
    },
    edmFn(row) {
      const newrow = { ...row }
      this.roleForm = newrow
      this.edit = true
      this.showDialog = true
    },
    submit() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          // 做具体的添加动作
          this.edit ? this.doEdit() : this.AddFn()
        }
      })
    },
    hSave() {
      this.$refs.assignPermission.hSave()
    },
    hcloseit() {
      this.showDialogAssign = false
    },
    hClose() {
      // 重置表单
      this.roleForm = {
        // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>

<style>
</style>
